package com.example.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.question.*;
import com.example.domain.question.dto.QuestionQueryDTO;
import com.example.domain.question.es.QuestionES;
import com.example.elasticsearch.QuestionRepository;
import com.example.manager.QuestionCacheManager;
import com.example.mapper.question.QuestionMapper;
import com.example.mapper.user.UserSubmitMapper;
import com.example.redis.service.RedisService;
import com.example.service.question.IQuestionServer;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.CacheConstants;
import oj.common.core.domain.PageQueryDTO;
import oj.common.core.domain.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class QuestionServerImpl implements IQuestionServer {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;
    @Autowired
    private RedisService redisService;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage =  questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage =  questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            questionESPage =  questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if(questionES != null) {
            //此时需要从数据库查询
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if(question==null) {
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public String preQuestionDetail(Long examId) {
        //先计算出这个题目在list中的位置，再进行拿到上一个题目的id
        Long count = questionCacheManager.getListSize();
        if(count==null || count<=0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.preQuestion(examId).toString();
    }

    @Override
    public String nextQuestionDetail(Long examId) {
        Long count = questionCacheManager.getListSize();
        if(count==null || count<=0) {
            questionCacheManager.refreshCache();
        }
        return questionCacheManager.nextQuestion(examId).toString();
    }

    /**
     * 热榜排行
     * @param pageQueryDTO
     * @return
     */
    @Override
    public List<HotQuestionVO> selectQuestionList(PageQueryDTO pageQueryDTO) {
        //先从数据库中拿redis中拿取数据，如果没有拿到的话从数据库中拿取数据，同时再将数据刷新到redis中
        long count = questionCacheManager.getHotQuestionListSize();
        List<HotQuestionVO> questionVOList ;
        if(count<=0) {
            PageHelper.startPage(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());
            List<HotQuestion> hotQuestionList = userSubmitMapper.selectHotQuestion(pageQueryDTO);
            List<Long> hotQuestionIds = hotQuestionList.stream().map(HotQuestion::getQuestionId).toList();
            questionVOList = questionMapper.selectHotQuestionTitle(hotQuestionIds);
            questionCacheManager.refreHotQuestion(questionVOList);
            return questionVOList;
        } else {
            log.info("查询数据库");
            questionVOList = redisService.getCacheListByRange(CacheConstants.QUESTION_HOST_LIST,
                    pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize(), HotQuestionVO.class);
        }
        return questionVOList;
    }

    public void refreshQuestion() {
        List<Question> questionList =
                questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if(CollectionUtil.isEmpty(questionList)) {
            return ;
        }
        List<QuestionES> questionES = BeanUtil.copyToList(questionList, QuestionES.class);
        questionRepository.saveAll(questionES);
    }
}
